//app.js
App({
  onLaunch: function (obj) {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },

  onShow: function (obj) {
    this.app_options = obj
    // const that = this
    // wx.getShareInfo({
    //   shareTicket: obj.shareTicket,
    //   success: function(res){
    //     console.log(obj.shareTicket)
    //     that.request({
    //       url: that.root + 'auth/getgid',
    //       method: 'post',
    //       data: {
    //         encryptedData: res.encryptedData,
    //         iv: res.iv
    //       },
    //       success: function (res) {
    //         that.gid = res.data.gid;
    //         console.log(that.gid)
    //       }
    //     })
    //   }
    // })
  },

  request: function (arg) {
    const that = this
    wx.getStorage({
      key: 'session_id',
      success: function (res) {
        wx.checkSession({
          success: function () {
            //session 未过期，并且在本生命周期一直有效
            that.req(arg, res.data)
          },
          fail: function () {
            //登录态过期
            that.login(arg)
          }
        })
      },
      fail: function () {
        that.login(arg)
      }
    })
  },

  login: function (arg) {
    const that = this
    wx.login({
      success: function (res) {
        if (res.code) {
          const code = res.code
          wx.getUserInfo({
            success: function (res) {
              wx.request({
                url: that.root + 'auth/login',
                method: 'POST',
                data: {
                  code: code,
                  rawData: res.rawData,
                  signature: res.signature,
                  encryptedData: res.encryptedData,
                  iv: res.iv
                },
                success: function (res) {
                  if (!res.data.err) {
                    that.req(arg, res.data.session_id)
                    //use sync to make sure next request can get session id
                    wx.setStorageSync('session_id', res.data.session_id)
                  }
                }
              })
            },
            fail: function (res) {
              that.reAuth(arg)
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function (res) {
        console.log('ss'+res)
      }
    });
  },

  reAuth: function(arg){
    const that = this
    wx.showModal({
      title: '提示',
      content: '请同意授权才能使用此应用',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.openSetting({
            success: function (res) {
              if (res.authSetting['scope.userInfo'] == true) {
                that.login(arg)
              } else {
                that.reAuth(arg)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          that.reAuth(arg)
        }
      }
    })
  },

  req: function (arg, session_id) {
    const that = this
    const success = arg.success
    arg.header = Object.assign(arg.header || {}, { 'session-id': session_id })
    arg.success = function (res) {
      //  dont have session on server
      if (res.data.err == 2) {
        that.login(arg)
        return
      }
      typeof success == "function" && success(res)
    }
    arg.fail = function (res){
      console.log(res)
    }
    wx.request(arg)
  },

  socket: function (arg) {
    const that = this
    const url = 'wss://wx.hnw.net/chatRoom'
    wx.connectSocket({
      url: url,
      fail: function (res) {
        console.log(res)
        wx.closeSocket()
        wx.connectSocket({
          url: url
        })
        typeof arg.fail == "function" && arg.fail(res)
      },
    })

    wx.onSocketOpen(function (res) {
      typeof arg.open == "function" && arg.open(res)
    })

    wx.onSocketError(function (res) {
      typeof arg.error == "function" && arg.error(res)
    })

    wx.onSocketMessage(function (res) {
      // console.log(res)
      const data = JSON.parse(res.data)
      if (data.type == 'init') {
        arg.init = arg.init || {}
        arg.init.method = 'post'
        arg.init.data = Object.assign(arg.init.data || {}, data, { 'gid': arg.gid || 1 })
        arg.init.url = arg.init.url || that.root + 'auth'
        that.request(arg.init)

        // that.request({
        //   method: 'post',
        //   url: that.root + 'gateway_worker/bind',
        //   data: Object.assign(data, { 'gid': arg.gid }),
        //   success: function () {
        //     typeof arg.link == "function" && arg.link(data.client_id)
        //   }
        // })
      } else if (data.type == 'ping') {
        wx.sendSocketMessage({
          data: 'pong',
        })
      } else if (data.type == 'close') {
        typeof arg.close == "function" && arg.close(data.client_id)
      } else {
        typeof arg.success == "function" && arg.success(data)
      }
    })
  },

  getUserInfo: function (cb) {
    const that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.getUserInfo({
        withCredentials: false,
        success: function (res) {
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },

  globalData: {
    userInfo: null
  },

  root: 'https://wx.hnw.net/ws/yue/'
})
